﻿using BBICMS.Infrastructure.UI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;

namespace BBICMS.Infrastructure
{
    public static class HtmlHelpers
    {

        public static MvcHtmlString PageLinks(this HtmlHelper html, PagingInfo pagingInfo, Func<int, string> pageUrl)
        {
            var pagingBuilder = new PagingHtmlBuilder();
            StringBuilder result = new StringBuilder();
            //previous link
            string prevLink = (pagingInfo.CurrentPage == 1)
                ? pagingBuilder.buildHtmlItem(pageUrl(pagingInfo.CurrentPage - 1), "<", false, true)
                : pagingBuilder.buildHtmlItem(pageUrl(pagingInfo.CurrentPage - 1), "<");
            result.Append(prevLink);

            // only show up to 5 links to the left of the current page
            var start = (pagingInfo.CurrentPage <= 6) ? 1 : (pagingInfo.CurrentPage - 5);
            // only show up to 5 links to the right of the current page
            var end = (pagingInfo.CurrentPage > (pagingInfo.TotalPages - 5)) ? pagingInfo.TotalPages : pagingInfo.CurrentPage + 5;

            for (int i = start; i <= end; i++)
            {
                string pageHtml;
                pageHtml = (i == pagingInfo.CurrentPage)
                    ? pagingBuilder.buildHtmlItem(pageUrl(i), i.ToString(), true)
                    : pagingBuilder.buildHtmlItem(pageUrl(i), i.ToString());
                result.Append(pageHtml);
            }

            // next link
            string nextLink = (pagingInfo.CurrentPage == pagingInfo.TotalPages)
                ? pagingBuilder.buildHtmlItem(pageUrl(pagingInfo.CurrentPage + 1), ">", false, true)
                : pagingBuilder.buildHtmlItem(pageUrl(pagingInfo.CurrentPage + 1), ">");
            result.Append(nextLink);

            return MvcHtmlString.Create(result.ToString());
        } 
    }
}
